﻿/**
* CRL
*/
using System;
using System.Collections.Generic;
using System.Text;

namespace CRL.EventBus
{
    public class SubscribeAttribute : System.Attribute
    {
        public SubscribeAttribute()
        {

        }
        public SubscribeAttribute(string name)
        {
            Name = name;
        }
        /// <summary>
        /// 订阅的名称
        /// </summary>
        public string Name
        {
            get; set;
        }
        /// <summary>
        /// 批量订阅时条数
        /// </summary>
        public int BatchSize
        {
            get; set;
        } = 500;
        /// <summary>
        /// 自定义队列名,仅rabbitmq
        /// </summary>
        public string QueueName
        {
            get; set;
        }
        /// <summary>
        /// 轮循线程间隔时间
        /// </summary>
        public double ThreadSleepSecond { get; set; } = 1;
        /// <summary>
        /// 指定MQ类型，如果配置了多种
        /// </summary>
        public MQType MQType { get; set; }

        /// <summary>
        /// 消费重试次数
        /// DB类不指定则按无限次数
        /// </summary>
        public int RetryTimes { get; set; }

        /// <summary>
        /// 是否为延迟队列，仅rabbitmq,rocketmq
        /// </summary>
        public bool DelayQueue { get; set; }
        /// <summary>
        /// 重复发送间隔ms
        /// </summary>
        public int RetryInterval { get; set; }

        public string Remark { get; set; }

        /// <summary>
        /// 自定义重发间隔
        /// 返回-1则不重发
        /// </summary>
        public Func<IData, int> RetryPolicy { get; set; }

        public int GetDelayTime(IData data)
        {
            if (RetryTimes > 0 && data.RetryTimes >= RetryTimes)
            {
                return -1;
            }
            if (RetryPolicy == null)
            {
                RetryPolicy = (d) =>
                {
                    if (RetryInterval > 0)
                    {
                        return RetryInterval;
                    }
                    var delayMs = 500;
                    var k = d.RetryTimes;
                    //每10次重新开始
                    if (k > 0)
                    {
                        k = k % 10;
                    }
                    for (var i = 0; i <= k; i++)
                    {
                        delayMs += (int)(delayMs * 0.5);
                    }
                    Console.WriteLine(delayMs/1000);
                    return delayMs;
                };
            }
            var n = RetryPolicy(data);
            return n;
        }
    }
}
